<?php

namespace app\api\controller\mall;

use think\Db;
use think\Cache;

class Rebate extends CommonMall {
	public function lists()
	{
		// $this->member['id'] = 12;
		$page = input('page/d', 1);
		$pagesize = input('pagesize/d', 20);

		$data = $this->db->name('mall_order_fanli')
			->where(['user_id'=>$this->member_relang['id']])
			->page($page)
			->limit($pagesize)
			->order('id desc')
			->select();

		$goods = $this->db->name('mall_goods')->where(['id'=>['in', array_column($data, 'goods_id')]])->column('name,image', 'id');
		$orders = $this->db->name('mall_order')->where(['id'=>['in', array_column($data, 'order_id')]])->column('uid,total', 'id');
		$orderItems = $this->db->name('mall_order_item')->where(['id'=>['in', array_column($data, 'order_item_id')]])->column('num,price,sku', 'id');

		foreach ($data as &$value) {
			$value['type'] = $value['goods_id'] ? 1 : 2;
			$value['goods'] = $goods[$value['goods_id']]??false;
			$value['orders'] = $orders[$value['order_id']]??false;
			$value['order_item'] = $orderItems[$value['order_item_id']]??false;

			$value['create_time'] = date('Y-m-d H:i', $value['create_time']);
			$value['start_time'] = $value['start_time'] ? date('Y-m-d H:i', $value['start_time']) : '';
			$value['auto_time'] = $value['auto_time'] ? date('Y-m-d H:i', $value['auto_time']) : '';

			// 计算预计还需多少天
			$value['dec_day'] = round((100 - $value['fanlied_rate']) / $value['fanli_day_rate']);

			$value['fanli_day_rate'] = $value['fanli_day_rate'] . '%';
			$value['fanli_day_rate_add'] = $value['fanli_day_rate_add'] . '%';
			$value['fanlied_rate'] = $value['fanlied_rate'] . '%';

			if ($value['state'] == 0) {
				$value['state_text'] = '暂停';
			} else if ($value['state'] == -1) {
				$value['state_text'] = '失效';
			} else if ($value['state'] == 2) {
				$value['state_text'] = '已返完';
			} else {
				$value['state_text'] = $value['start_time'] ? '正常' : '等待收货';
			}

		}

		return $this->pass($data);
	}

	public function rebate_records()
	{
		// $this->member['id'] = 12;
		$id = input('id/d', 0);
		$page = input('page/d', 1);
		$pagesize = input('pagesize/d', 20);

		$fanli = $this->db->name('mall_order_fanli')->where(['id'=>$id, 'user_id'=>$this->member_relang['id']])->find();
		if (!$fanli) return $this->miss('记录不存在');

		$data = $this->db->name('mall_order_fanli_records')->where(['mall_order_fanli_id'=>$id])->page($page)->limit($pagesize)->order('id desc')->select();
		foreach ($data as &$value) {
			$value['time'] = date('Y-m-d H:i', $value['time']);
			$value['fanli_rate'] = $value['fanli_rate'] . '%';
		}
		return $this->pass($data);
	}

	public function rebate_lists()
	{
		// $this->member['id'] = 12;
		$page = input('page/d', 1);
		$pagesize = input('pagesize/d', 20);

		$fanli_ids = $this->db->name('mall_order_fanli')->where(['user_id'=>$this->member_relang['id']])->column('id');

		$data = $this->db->name('mall_order_fanli_records')->where(['mall_order_fanli_id'=>['in', $fanli_ids]])->page($page)->limit($pagesize)->order('id desc')->select();
		foreach ($data as &$value) {
			$value['time'] = date('Y-m-d H:i', $value['time']);
			$value['fanli_rate'] = $value['fanli_rate'] . '%';
		}
		return $this->pass($data);
	}

	public function accelerate()
	{
		// $this->member['id'] = 11;
		$id = input('id/d', 0);
		$fanli = $this->db->name('mall_order_fanli')->master()->where(['id'=>$id])->find();
		if (!$fanli) return $this->miss('记录不存在');
		if ($fanli['state']!=1) return $this->miss('状态异常');
		if ($fanli['user_id']==$this->member_relang['id']) return $this->miss('不能给自己助力');
		if ($fanli['fanli_day_rate_add']>=0.05) return $this->miss('好友项目助力已达上限');

		$hasHelp = $this->db->name('mall_order_fanli_help')->master()->where(['mall_order_fanli_id'=>$id, 'user_id'=>$this->member_relang['id']])->find();
		if ($hasHelp) return $this->miss('你已经帮忙加速过了~');
		$fanli_rate = rand(1,10) / 10000;

		$this->db->name('mall_order_fanli_help')->insert(['mall_order_fanli_id'=>$id, 'user_id'=>$this->member_relang['id'], 'fanli_rate'=>$fanli_rate, 'time'=>time()]);
		$this->db->name('mall_order_fanli')->where(['id'=>$id])->update([
			'fanli_day_rate'=>Db::raw('fanli_day_rate+'.$fanli_rate),
			'fanli_day_rate_add'=>Db::raw('fanli_day_rate_add+'.$fanli_rate)
		]);

		return $this->pass("成功帮好友加速了$fanli_rate%");
	}

	public function accelerate_records()
	{
		// $this->member['id'] = 12;
		$id = input('id/d', 0);
		$page = input('page/d', 1);
		$pagesize = input('pagesize/d', 20);
		$fanli = $this->db->name('mall_order_fanli')->master()->where(['id'=>$id])->find();
		if (!$fanli) return $this->miss('记录不存在');
		$data = $this->db->name('mall_order_fanli_help')->where(['mall_order_fanli_id'=>$id])->page($page)->limit($pagesize)->select();

        $users = $this->db->name('user')
                        ->alias('u')
                        ->join('user_channel_profile cp', 'u.id=cp.user_id and sys_channel='.getenv('APP_CHANNEL'), 'left')
                        ->where(['u.id' => ['in', array_column($data, 'user_id')]])->cache(60)->column('COALESCE(cp.name, u.name) as name,COALESCE(cp.head_portrait, u.head_portrait) as head_portrait', 'u.id');
                        
		foreach ($data as &$value) {
			$value['user'] = $users[$value['user_id']]??false;
			$value['time'] = date('Y-m-d H:i', $value['time']);
			$value['fanli_rate'] = $value['fanli_rate'] . '%';
		}

		return $this->pass($data);
	}

	public function info()
	{
		$id = input('id/d', 0);
		$info = $this->db->name('mall_order_fanli')->master()->where(['id'=>$id])->find();
		if (!$info) return $this->miss('记录不存在');

		$info['type'] = $info['goods_id'] ? 1 : 2;
		$info['create_time'] = date('Y-m-d H:i', $info['create_time']);
		$info['start_time'] = $info['start_time'] ? date('Y-m-d H:i', $info['start_time']) : '';
		$info['auto_time'] = $info['auto_time'] ? date('Y-m-d H:i', $info['auto_time']) : '';
		// 计算预计还需多少天
		$info['dec_day'] = round((100 - $info['fanlied_rate']) / $info['fanli_day_rate']);

		$info['fanli_day_rate'] = $info['fanli_day_rate'] . '%';
		$info['fanli_day_rate_add'] = $info['fanli_day_rate_add'] . '%';
		$info['fanlied_rate'] = $info['fanlied_rate'] . '%';



		if ($info['goods_id']) {
			$info['goods'] = $this->db->name('mall_goods')->where(['id'=>$info['goods_id']])->field('name,image,id')->find();
		}
		if ($info['order_id']) {
			$info['orders'] = $this->db->name('mall_order')->where(['id'=>$info['order_id']])->field('uid,total,id')->find();
        	$info['orders']['user'] = $this->db->name('user')
                        ->where(['id' => $info['orders']['uid']])
                        ->field('name,head_portrait,id')
                        ->find();
		}
		if ($info['order_item_id']) {
			$info['order_item'] = $this->db->name('mall_order_item')->where(['id'=>$info['order_item_id']])->field('num,price,sku,id')->find();
		}


		if ($info['state'] == 0) {
			$info['state_text'] = '暂停';
		} else if ($info['state'] == -1) {
			$info['state_text'] = '失效';
		} else if ($info['state'] == 2) {
			$info['state_text'] = '已返完';
		} else {
			$info['state_text'] = $info['start_time'] ? '正常' : '等待收货';
		}

		$hasHelp = $this->db->name('mall_order_fanli_help')->master()->where(['mall_order_fanli_id'=>$id, 'user_id'=>$this->member_relang['id']])->find();
		$info['is_accelerate'] = $hasHelp?true:false;

		return $this->pass($info);
	}

	public function wallet()
	{
		// $this->member['id'] = 12;

		$frozen = $this->db->name('mall_order_fanli')->where(['user_id'=>$this->member_relang['id'], 'state'=>1])->field('fanli_count,fanlied_count')->select();
		$frozen_count = array_sum(array_column($frozen, 'fanli_count')) - array_sum(array_column($frozen, 'fanlied_count'));

		$unfrozen_count = $this->db->name('mall_order_fanli')->where(['user_id'=>$this->member_relang['id']])->sum('fanlied_count');

		return $this->pass(compact('frozen_count', 'unfrozen_count'));
	}

	public function loop()
	{
		$rebateCacheCount = 'rebateCacheCount';
        $count = Cache::store('redisUnclear')->get($rebateCacheCount);
        
		$rebateCacheToday = 'rebateCacheToday';
        $today = Cache::store('redisUnclear')->get($rebateCacheToday);

		$rebateCacheList = 'rebateCacheList';
        $list = Cache::store('redisUnclear')->get($rebateCacheList);
		$time = time();
		$today_start = strtotime(date('Y-m-d'));
		$daysum = 0;
        if (!$list) {
			$user = Db::name('user')->where(['delete_time'=>0, 'is_banned'=>0, 'reg'=>1])->whereTime('last_login_time', '-30 day')->limit(50)->column('name');
			$list = [];
			foreach ($user as $key => $value) {
				$money = rand(1,23) / 100;
				$count += $money;
				$daysum += $money;

				$list[] = mb_substr($value, 0, 1) . '*** 于 ' . date('Y-m-d H:i:s', $time - $key * rand(20,60)) . ' 返还 '.$money.'元';
			}
			Cache::store('redisUnclear')->set($rebateCacheList, $list, 1800);
        }
		if ($today_start + 600 > $time && $time > $today_start) {
			$today = $daysum;
		} else {
			$today += $daysum;
		}
		$count = round($count, 2);
		$today = round($today, 2);
		Cache::store('redisUnclear')->set($rebateCacheCount, $count, 86400);
		Cache::store('redisUnclear')->set($rebateCacheToday, $today, 86400);

		return $this->pass(compact('count', 'today', 'list'));
	}
}